package cn.sitcat.springbootrestfulcrud.controller;

import cn.sitcat.springbootrestfulcrud.dao.DepartmentDao;
import cn.sitcat.springbootrestfulcrud.dao.EmployeeDao;
import cn.sitcat.springbootrestfulcrud.entities.Department;
import cn.sitcat.springbootrestfulcrud.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

/**
 * @author hiseico
 * @date 2019/1/26 19:58
 * @desc
 */
@Controller
public class EmployessController {
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private DepartmentDao departmentDao;

    //        查询所有员工返回列表页面
    @GetMapping("/emps")
    public String list(Model model) {
        Collection<Employee> allUserList = employeeDao.getAll();
        model.addAttribute("emps", allUserList);
        //thymeleaf会对返回路径自动拼接：classpath:/template/xxx.html
        return "emp/list";
    }

    /**
     * 来到员工添加页面
     *
     * @return
     */
    @GetMapping("emp")
    public String toAdd(Model model) {
//        查出所有的部门
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts", departments);
//        来到添加页面
        return "emp/add";
    }

    /**
     * 员工添加
     *
     * @param employee
     * @return
     */
    @PostMapping("/emp")
    public String addEmp(Employee employee) {
//      保存员工
        employeeDao.save(employee);
//        回到员工列表页面
//        redirect 表示重定向到一个Controller地址   /代表当前项目路径
//        forward 表示转发到一个Controller地址
        return "redirect:/emps";
    }

    /**
     * 进入修改页面
     *
     * @return
     */
    @GetMapping("/emp/{id}")
    public String toEdit(@PathVariable("id") Integer id, Model model) {
        Employee employee = employeeDao.get(id);
        model.addAttribute("emp", employee);

        //查出所有的部门
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts", departments);
//        回到编辑页面
        return "emp/add";
    }

    @PutMapping("/emp")
    public String edit(Employee employee) {
        System.out.println("修改的员工数据：" + employee);

        employeeDao.save(employee);
        return "redirect:/emps";
    }

    @DeleteMapping("/emp/{id}")
    public String deleteEmp(@PathVariable("id") Integer id) {
        employeeDao.delete(id);
        return "redirect:/emps";
    }
}
